import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { SupplierInput, ProfileServiceProxy, DataItemDetailModel, DataItemServiceProxy, DataItemDetailInputDto } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { IOrganizationUnitsTreeComponentData, OrganizationUnitsTreeComponent } from '../../shared/organization-unit-tree.component';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { SelectItem } from 'primeng/api';

@Component({
  selector: 'DataItemDetailCreate',
  templateUrl: './DataItemDetailCreate.component.html',
  styleUrls: ['./DataItemDetailCreate.component.css']
})

export class DataItemDetailCreateComponent extends AppComponentBase {
  @ViewChild('createOrEditModal') modal: ModalDirective;
  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;
  itemAyy = [];
  selectedItem: string;
  ItemDetail: DataItemDetailModel = new DataItemDetailModel();
  constructor(injector: Injector,
    private _dataItemServiceProxy: DataItemServiceProxy,
    private _profileService: ProfileServiceProxy) {
    super(injector);
  }
  show(ItemDetailId?: string, selectedItem?: string): void {
    console.log(ItemDetailId);
    console.log(selectedItem);
    this.selectedItem = selectedItem;
    if (!ItemDetailId) {
        this.active = true;
    }

    this._dataItemServiceProxy.getDataItemDetailForEdit(ItemDetailId).subscribe(resultdata => {
        this.ItemDetail = resultdata;
        console.log(resultdata);
        if (ItemDetailId) {
            this.active = true;
        }
        this.modal.show();
    });
    // this.active = true;
    // this.modal.show();
}
  onShown(): void {
    this._dataItemServiceProxy.getDataItemAllList().subscribe(resultdata => {
      this.itemAyy = resultdata;
      if(!this.selectedItem)
      {
        this.selectedItem = this.itemAyy[0].value;
      }
    });
  }
  
  save(): void {
    console.log(this.selectedItem);
    this.ItemDetail.itemId = this.selectedItem;
    let input = new DataItemDetailInputDto();
    input.model = this.ItemDetail; 
    this.saving = true;
    console.log(input);
    this._dataItemServiceProxy.createOrUpdateDataItemDetail(input)
        .pipe(finalize(() => { this.saving = false; }))
        .subscribe(() => {
            this.notify.info(this.l('SavedSuccessfully'));
            this.close();
            this.modalSave.emit(null);
        });
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }
}

